package com.example.myapplication.util

import java.text.SimpleDateFormat
import java.time.OffsetDateTime
import java.util.Date
import java.util.Locale

object DateTimeParser {
    
    /**
     * 解析 ISO 8601 格式的日期时间字符串
     * 支持格式: 2025-08-19T09:43:14+08:00
     */
    fun parseIsoDateTime(dateTimeString: String): Date {
        return if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            // Android O (API 26) 及以上使用新的 DateTime API
            parseWithDateTimeApi(dateTimeString)
        } else {
            // 旧版本使用 SimpleDateFormat
            parseWithSimpleDateFormat(dateTimeString)
        }
    }
    
    @android.annotation.SuppressLint("NewApi")
    private fun parseWithDateTimeApi(dateTimeString: String): Date {
        val offsetDateTime = OffsetDateTime.parse(dateTimeString)
        return Date.from(offsetDateTime.toInstant())
    }
    
    private fun parseWithSimpleDateFormat(dateTimeString: String): Date {
        val formatter = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.getDefault())
        return formatter.parse(dateTimeString)
    }

    fun parseTimeToLocalString(dateTimeString: String): String {
        val parseIsoDateTime = parseIsoDateTime(dateTimeString)
        return toLocalString(parseIsoDateTime)
    }


    /**
     * 转换为本地时间字符串
     */
    fun toLocalString(date: Date, pattern: String = "yyyy-MM-dd HH:mm:ss"): String {
        val formatter = SimpleDateFormat(pattern, Locale.getDefault())
        return formatter.format(date)
    }

    /**
     * 时间戳格式化
     */
    fun timeToLocalString(time: Long, pattern: String = "yyyy-MM-dd HH:mm:ss"): String {
        return toLocalString(timeToDate(time), pattern)
    }
    
    /**
     * 获取时间戳（毫秒）
     */
    fun getTimestamp(dateTimeString: String): Long {
        return parseIsoDateTime(dateTimeString).time
    }

    /**
     * time 转 date
     */
    fun timeToDate(time: Long): Date {
        return Date(time)
    }
}

// 使用示例
fun main() {
    val dateString = "2025-08-19T09:43:14+08:00"
    
    try {
        // 解析为 Date 对象
        val date = DateTimeParser.parseIsoDateTime(dateString)
        println("Date 对象: $date")
        
        // 转换为本地时间格式
        val localTime = DateTimeParser.toLocalString(date)
        println("本地时间: $localTime")
        
        // 获取时间戳
        val timestamp = DateTimeParser.getTimestamp(dateString)
        println("时间戳: $timestamp")
        
    } catch (e: Exception) {
        println("解析失败: ${e.message}")
    }
}